


import    urllib2,urllib,re,sys,os
import    xbmc, xbmcaddon, xbmcgui, xbmcplugin
import    time



def getRequest(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()
    return link

def getVideoUrl(url):
    link = getRequest('http://www.youtube.com/watch?v='+url+'&safeSearch=none&hl=en_us')
    fmtSource = re.findall('"url_encoded_fmt_stream_map": "([^"]+)"', link)
    fmtSource[0] = fmtSource[0][4:]
    fmt_url_map = urllib.unquote_plus(fmtSource[0]).split(',url=')

    for fmt_url in fmt_url_map:
        url = fmt_url.replace('\u0026','&')
        quality = url[url.rfind('&itag=')+6:]
        if(url.find('&itag=')!=url.rfind('&itag=')):
            url = url[:url.rfind('&itag=')]
        if (url.rfind('; codecs')>0):
            url = url[:url.rfind('; codecs')]
        name_quality = url[url.find("&quality=")+9 : ]
        name_quality = name_quality[ : name_quality.find("&")]
        if(len(name_quality) == 0):
            name_quality = "Undefined"
        addVideo("Quality: " + name_quality, url)

def getParams(paramList):
    splitParams = paramList[paramList.find('?')+1:].split('&')
    paramsFinal = {}
    for value in splitParams:
        splitParams = value.split('=')
        type = splitParams[0]
        content = splitParams[1]
        if type == 'url':
            content = urllib.unquote_plus(content)
        paramsFinal[type] = content
    return paramsFinal

def addCategory(title, url, action, page="0", count = 0):
    url=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&title="+urllib.quote_plus(title)+"&action="+urllib.quote_plus(action)+"&page="+urllib.quote_plus(page)
    listitem=xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    listitem.setInfo( type="Video", infoLabels={ "Title": title } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True, totalItems=count)

def addVideo(title, url):
    liz=xbmcgui.ListItem(title, "DefaultVideo.png", thumbnailImage="DefaultVideo.png")
    liz.setInfo( type="Video", infoLabels={ "Title": title } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)


def root():
    addCategory("Warcraft III",     "http://goodgame.ru/?warcraftiii", "0", "0")
    addCategory("Starcraft 2",      "http://goodgame.ru/?starcraft2", "0", "0")
    addCategory("Dota",             "http://goodgame.ru/?dota", "0", "0")
    addCategory("Dota 2",           "http://goodgame.ru/?dota2", "0", "0")
    addCategory("Quake Live",       "http://goodgame.ru/?quake-live", "0", "0")
    addCategory("Counter Strike",   "http://goodgame.ru/?counter-strike", "0", "0")

def content(url, page):
    cookies = ""
    while (cookies == ""):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        headers = response.info()
        response.close()
        try:
            cookies = headers["Set-Cookie"]
        except:
            time.sleep(7)

    req = urllib2.Request('http://goodgame.ru/video.php?rpp=10&pg=' + page)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
    req.add_header('Cookie', cookies)
    response = urllib2.urlopen(req)
    page = response.read()
    response.close()
    page2 = page

    page = page[page.find("VideoRecs") : page.rfind("VideoRecs")]

    icons = re.compile("img src=\'\.(.+?)\' alt").findall(page)
    names = re.compile("blue_event\'><b>(.+?)</b></a>").findall(page)
    links = re.compile("<a href=\'(.+?)\' class=\'main_pg_block\'").findall(page)

    for i in range(len(links)):
        links[i] = "http://goodgame.ru" + links[i]
        icons[i] = "http://goodgame.ru" + icons[i]

        req = urllib2.Request(links[i])
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        page = response.read()

        page = page[page.find("main_descr"):]

        if(page.find("youtube.com")>=0):
            page = re.compile("http://www.youtube.com.+?\"").findall(page)
            page = list(set(page))
            if (len(page) == 1):
                code = page[0][25 : 36]
                addCategory(names[i], code, "1")
            else:
                for j in range(len(page)):
                    code = page[j][25 : 36]
                    addCategory(names[i] + "  [Part " + repr(j+1) +"]", code, "1")

        elif (page.find("http://www.own3d.tv")>=0):
            link = re.compile("http://www.own3d.tv.+?\"").findall(page)[0]
            addVideo(names[i], link)
        elif(page.find("http://www.gomtv.net")>=0):
            link = re.compile("http://gomtv.net.+?\"").findall(page)[0]
            addVideo(names[i], link)
        elif(page.find("http://stream.goodgame.ru")>=0):
            link = re.compile("http://stream.goodgame.ru.+?.f.+?v").findall(page)[0]
            addVideo(names[i], link)
        time.sleep(1)


    page2 = page2[page2.find("nav_opts") : page2.find("rarr")]

    if(len(page2)>0):
        page = page2[page2.rfind("/video.php"): ]
        page = page[14 : page.find("\'")]
        addCategory("Get more...", url, "0", page)
        time.sleep(3)

if (not sys.argv[2]):
    root()
else:
    params_list = getParams(sys.argv[2])

    if (params_list["action"] == "0"):
        content(params_list["url"], params_list["page"])
    if(params_list["action"]=="1"):
        getVideoUrl(params_list["url"])


xbmcplugin.endOfDirectory(int(sys.argv[1]))
